/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.sober.sequences.impl;


import com.jspx.sober.sequences.Sequences;
import com.jspx.sober.sequences.SequencesDAO;
import com.jspx.sober.annotation.Id;
import com.jspx.sober.SoberSupport;
import com.jspx.utils.BooleanUtil;
import com.jspx.utils.StringUtil;

import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 * User:chenYuan (mail:39793751@qq.com)
 * Date: 2005-9-11
 * Time: 18:47:27
 * jspx.user.dao.aop.SequencesDAOImpl
 */
public class SequencesDAOImpl implements SequencesDAO
{
    private SoberSupport soberSupport = null;

    public SequencesDAOImpl(SoberSupport soberSupport)
    {
        this.soberSupport = soberSupport;
    }

    public String getNextKey(String keyName, Id idf) throws Exception
    {
        String result;
        Sequences tableSequences = (Sequences) soberSupport.get(Sequences.class, keyName);
        if (tableSequences != null)
        {
            result = tableSequences.getNextKey();
            if (soberSupport.update(tableSequences, new String[]{"keyValue"}) < 1)
            {
                return Math.abs(UUID.randomUUID().getMostSignificantBits()) + StringUtil.empty;
            }
        } else
        {
            tableSequences = new Sequences();
            tableSequences.setName(keyName);
            tableSequences.setKeyLength(idf.length());
            tableSequences.setKeyMax(idf.max());
            tableSequences.setKeyMin(idf.min());
            tableSequences.setKeyNext(idf.next());
            tableSequences.setKeyValue(idf.min());
            tableSequences.setAdddate(BooleanUtil.toInt(idf.dateStart()));
            soberSupport.save(tableSequences, false);
            tableSequences = (Sequences) soberSupport.get(Sequences.class, keyName);
            result = tableSequences.getNextKey();
            soberSupport.update(tableSequences, new String[]{"keyValue"});
        }
        return result;
    }

}